<?php

namespace app\mp\admin;

use app\system\admin\Admin;
use think\Db;
use app\common\service\CostCheck as CostCheckService;

/**
 * 成本管理-核价与补损跟进表
 * @author zhuguosen 905502314@qq.com
 * @date 2022/6/28
 * @package app\mp\admin
 */
class CostCheck extends Admin
{
    private $typeMap;
    private $type_0Map;
    private $type_10000Map;
    /**
     * @var \app\common\service\CostCheck
     */
    private $costCheckService;

    public function initialize()
    {
        parent::initialize();
//        $this->typeMap = [0 => '加工费', 1 => '面辅料', 2 => '单件用量', 3 => '工艺染色',
//            10000 => '幅宽补损', 10001 => '公斤补损', 10002 => '米数补损',];
        $this->type_0Map = [0 => '加工费', 1 => '面辅料', 2 => '单件用量', 3 => '工艺染色',];
        $this->type_10000Map = [10000 => '幅宽补损', 10001 => '公斤补损', 10002 => '米数补损',];
        $this->typeMap = $this->type_0Map + $this->type_10000Map;
        $typeMapSelect = [];
        foreach ($this->type_0Map as $k => $v) {
            $typeMapSelect[$k + 1] = $v;
        }
        $typeMapSelect_10000 = [];
        foreach ($this->type_10000Map as $k => $v) {
            $typeMapSelect_10000[$k + 1] = $v;
        }
        $this->assign('typeMap', $this->type_0Map);
        $this->assign('typeMapSelect', ['' => '请选择'] + $typeMapSelect);
        $this->assign('type_10000Map', $this->type_10000Map);
        $this->assign('typeMapSelect_10000', ['' => '请选择'] + $typeMapSelect_10000);
        $this->costCheckService = new CostCheckService();
    }

    /**
     * 核价跟进
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/28
     */
    public function index($status = 0, $template = 'index')
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $where = $this->_where_index([$status]);
            $field = "cc.id,cc.type,cc.return_num,cc.order_material_id,cc.order_id,cc.client_ordernum
                ,cc.remark,cc.param1,cc.param2,cc.admin_id,cc.update_time ,cc.update_time_0,cc.create_time as check_create_time
                ,ext.cost_little
                ,ext.special_process_a_name,ext.special_process_a_unitprice
                ,o.sku,o.create_time
                ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                ,ft.name as factory_name
,group_concat(distinct os.mid,',', os.size_name,',',os.order_count ,',',os.shicai_count,',',os.jiaohuo_count,',',os.jiaohuo_tail_count,',',os.delivery_count,',',os.daohuo_count  SEPARATOR ';') as order_size_list
                ,s.pic,s.ori_pic
                ,m.type as material_type ,m.name as material_name
                ,om.customer_price
                ,su.username as admin_id_username
                ,om.caigou_unitprice,om.customer_price
                ,om.caichuang_shiji_dosage,om.customer_dosage
                ";
            $list = db('cost_check cc')
                ->field($field)
                ->join('order o', 'cc.order_id=o.id', 'left')
                ->join('order_ext ext', 'cc.order_id=ext.order_id', 'left')
                ->join('factory ft', 'o.factory_id=ft.id', 'left')
                ->join('sku s', 'o.sku=s.sku', 'left')
                ->join('order_size os ', 'o.id=os.order_id', 'left')
                ->join('order_material om', 'cc.order_material_id=om.mid', 'left')
                ->join('material m', 'om.material_id=m.id', 'left')
                ->join('system_user su', "cc.admin_id=su.id", 'left')
                ->where($where)
                ->page($page)->limit($limit)
                ->group('cc.id')
                ->orderRaw('cc.id desc')
                ->select();
            $count = db('cost_check cc')
                ->join('order o', 'cc.order_id=o.id', 'left')
                ->join('order_ext ext', 'cc.order_id=ext.order_id', 'left')
                ->join('factory ft', 'o.factory_id=ft.id', 'left')
                ->join('sku s', 'o.sku=s.sku', 'left')
                ->join('order_size os ', 'o.id=os.order_id', 'left')
                ->join('order_material om', 'cc.order_material_id=om.mid', 'left')
                ->join('material m', 'om.material_id=m.id', 'left')
                ->join('system_user su', "cc.admin_id=su.id", 'left')
                ->where($where)
                ->group('cc.id')
                ->count();
            foreach ($list as $k => $v) {
                $list[$k]['osList'] = $osList = $this->_deal_order_size_list($v['order_size_list']);
                $list[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                $list[$k]['status_txt'] = $this->_get_order_status_txt($v);
                //原价/数量  差价金额
                $list[$k]['source_price'] = '';
                $list[$k]['chae_txt'] = '';
                switch ($v['type']) {
                    case 0:
                        $list[$k]['source_price'] = "{$v['cost_little']}";
                        $list[$k]['chae_txt'] = $v['param1'] > 0 ? $v['param1'] - $v['cost_little'] : '';
                        break;
                    case 1:
                        $list[$k]['source_price'] = "采购单价：{$v['caigou_unitprice']}<br/>
                                                     客户单价：{$v['customer_price']}";
                        $chae_txt_1 = $v['param1'] > 0 ? $v['param1'] - $v['caigou_unitprice'] : '';
                        $chae_txt_2 = $v['param2'] > 0 ? $v['param2'] - $v['customer_price'] : '';
                        $list[$k]['chae_txt'] = "采购单价：{$chae_txt_1}<br/>
                                                     客户单价：{$chae_txt_2}";
                        break;
                    case 2:
                        $list[$k]['source_price'] = "实际用量：{$v['caichuang_shiji_dosage']}<br/>
                                                     客户用量：{$v['customer_dosage']}";
                        $chae_txt_1 = $v['param1'] > 0 ? $v['param1'] - $v['caichuang_shiji_dosage'] : '';
                        $chae_txt_2 = $v['param2'] > 0 ? $v['param2'] - $v['customer_dosage'] : '';
                        $list[$k]['chae_txt'] = "实际用量：{$chae_txt_1}<br/>
                                                     客户用量：{$chae_txt_2}";
                        break;
                    case 3:
                        $list[$k]['source_price'] = "面辅二次工艺单价：<br/>{$v['special_process_a_unitprice']}";
                        $chae_txt_1 = $v['param1'] > 0 ? $v['param1'] - $v['special_process_a_unitprice'] : '';
                        $list[$k]['chae_txt'] = "面辅二次工艺单价：<br/>{$chae_txt_1}";
                        break;
                }
                $list[$k]['type_txt'] = $this->typeMap[$v['type']];
                //数据处理
                $list[$k]['factory_name'] = trim($v['factory_name']);
                $list[$k]['material_type'] = trim($v['material_type']);
                $list[$k]['material_name'] = trim($v['material_name']);
                $list[$k]['check_create_time']=date('Y-m-d H:i', $v['check_create_time']);
                $v['create_time'] > 0 ? $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']) : $list[$k]['create_time'] = '';
                $v['update_time'] > 0 ? $list[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']) : $list[$k]['update_time'] = '';
                $v['update_time_0'] > 0 ? $list[$k]['update_time_0'] = date('Y-m-d H:i:s', $v['update_time_0']) : $list[$k]['update_time_0'] = '';
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
            ];
            return json($result);
        }
        $factoryKV = getFactoryKV(false);
        $this->assign('factoryKV', [0 => '请选择'] + $factoryKV);
        $this->assign('status', $status);
        return $this->fetch($template);
    }

    private function _where_index($status)
    {
        $where = [];
        $where[] = ['cc.status', 'in', $status];
        $where[] = ['cc.type', '<', 10000];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $createDateRange = $this->request->param('create_date_range/s', '');
        $type = $this->request->param('type/d', 0);
        $factorId = $this->request->param('factory_id/d', 0);
        if ($clientOrdernum != '') {
            $where[] = ['cc.client_ordernum', '=', $clientOrdernum];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factorId) {
            $where[] = ['o.factory_id', '=', $factorId];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($type > 0) {
            $where[] = ['cc.type', '=', $type - 1];
        }
        return $where;
    }

    private function _deal_order_size_list($order_size_list)
    {
        if (trim($order_size_list) == '') {
            return [];
        }
        $res = [];
        $list = explode(';', $order_size_list);
        foreach ($list as $k => $v) {
            $temp = explode(',', $v);
            $res[] = [
                'size_name' => $temp[1],
                'order_count' => $temp[2],
                'shicai_count' => $temp[3],
                'jiaohuo_count' => $temp[4],
                'jiaohuo_tail_count' => $temp[5],
                'delivery_count' => $temp[6],
                'daohuo_count' => $temp[7],
            ];
        }
        return $res;
    }

    //获取订单状态说明
    private function _get_order_status_txt($v)
    {
        $v['status'] = $v['order_status'];

        if ($v['status'] == 99) {
            return '已废弃';
        }
        if ($v['status'] == 99) {
            return 'MES废除';
        }
        if ($v['caigou_status'] == 0) {
            return '未采购';
        }
        if ($v['caigou_status'] == 1 && $v['caichuang_status'] == 0) {
            return '已采购';
        }
        if ($v['caichuang_status'] == 1 && $v['chejian_status'] == 0) {
            return '已裁床';
        }
        if ($v['chejian_status'] == 1 && $v['tail_status'] == 0) {
            return '已车缝';
        }
        if ($v['tail_status'] == 1 && $v['real_shipment_status'] == 0) {
            return '已后整';
        }
        if ($v['real_shipment_status'] == 1 && $v['status'] == 1) {
            return '已出货';
        }
        if ($v['status'] == 2) {
            return '已完成';
        }
        return '新单未处理';
    }

    public function add($type = 0, $template = 'add')
    {
        if ($this->request->isPost()) {
            $param = [
                'client_ordernum' => $this->request->param('client_ordernum/s', ''),
                'type' => $this->request->param('type/d', 0),
                'mid' => $this->request->param('mid/d', 0),
                'info1' => $this->request->param('info1/d', 0),
            ];
            //1.1,检测这订单号是否合法
            $order_info = db('order')->field('id,client_ordernum')->where(['client_ordernum' => $param['client_ordernum']])->find();
            if (!isset($order_info['id'])) {
                return $this->error('订单号不存在！');
            }
            //1.2,检查各类型的限制  10000 => '幅宽补损', 10001 => '公斤补损', 10002 => '米数补损'
            switch ($param['type']) {
                case 10000:
                case 10001:
                case 10002:
                    $c_info = db('cost_check')->where(['client_ordernum' => $param['client_ordernum'], 'type' => $param['type'], 'order_material_id' => $param['mid']])->find();
                    if (isset($c_info['id'])) {
                        return $this->error('此信息已存在，不能添加了');
                    }
                    break;
                default:
                    $c_info = db('cost_check')->where(['client_ordernum' => $param['client_ordernum'], 'type' => $param['type']])->find();
                    if (isset($c_info['id'])) {
                        return $this->error('此信息已存在，不能添加了');
                    }
                    break;
            }
            //0 => '加工费', 1 => '面辅料', 2 => '单件用量', 3 => '工艺染色',
            Db::startTrans();
            try {
                //1.3 查必要信息
                switch ($param['type']) {
                    case 1://查此订单所有物料信息
                    case 2:
                        $where = [
                            ['om.client_ordernum', '=', $param['client_ordernum']],
                            ['om.mid','=',$param['mid']]
                        ];
                        $list = db('order_material om')
                            ->field('om.mid,om.order_id,om.client_ordernum ,om.stock_m_type
                ,om.caigou_unitprice ,om.customer_price
                ,m.type
                ,cc.id as cc_id
                ')
                            ->join('material m', 'om.material_id=m.id', 'left')
                            ->join('cost_check cc', 'om.mid=cc.order_material_id and cc.type=1 ', 'left')
                            ->join('order o', 'om.order_id=o.id', 'left')
                            ->where($where)
                            ->whereRaw(" cc.id is null ")
                            ->select();
                        foreach ($list as $k => $v) {
                            $this->costCheckService->set_cost_check($param['type'], $v['stock_m_type'], $v['client_ordernum'], $v['mid']);
                        }
                        break;
                    case 10000:
                    case 10001:
                    case 10002:
                        $this->costCheckService->set_cost_check($param['type'], 0, $order_info['client_ordernum'], $param['mid'], $param);
                        break;
                    default:
                        $this->costCheckService->set_cost_check($param['type'], 0, $order_info['client_ordernum']);
                        break;
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error('设置失败', null, [$e->getFile(), $e->getLine(), $e->getMessage()]);
            }
            return $this->success('保存成功', '');
        }
        return $this->fetch($template);
    }

    public function add10000()
    {
        return $this->add(10000, 'add10000');
    }

    /**
     * 设置
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/29
     */
    public function addConfig()
    {
        $type = $this->request->param('type', 'add_config');
        if ($this->request->isPost()) {
            $param = [
                'type' => $this->request->param('type/d', 0),
                'type_percent' => $this->request->param('type_percent'),
                'm_type' => $this->request->param('m_type'),
            ];
            $savedata=[
                'type' => $param['type'],
                'content' => json_encode($param),
                'admin_id' => ADMIN_ID,
                'update_time' => time(),
                'create_time' => time(),
            ];
            $havedata=db('cost_check_config')->whereRaw("type=".$param['type'])->order('id desc')->find();
            //1,参数处理
            //10,插入数据
            if($havedata){
                db('cost_check_config')->whereRaw("type=".$param['type'])->update($savedata);
                return $this->success('保存成功', '');
            }
            db('cost_check_config')->insert($savedata);
            return $this->success('保存成功', '');
        }
        $config_0 = db('cost_check_config')->whereRaw("type=0")->order('id desc')->find();
        isset($config_0['id']) && $config_0 = json_decode($config_0['content'], true);
        $config_10000 = db('cost_check_config')->whereRaw("type=10000")->order('id desc')->find();
        isset($config_10000['id']) && $config_10000 = json_decode($config_10000['content'], true);
        $this->assign('config_0', $config_0);
        $this->assign('config_10000', $config_10000);
        return $this->fetch($type);
    }

    /**
     * 节点状态改变
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/29
     */
    public function check()
    {
        $type_name = $this->request->param('type_name/s', 'hejia');
        $status = $this->request->param('status/d', 0);
        $ids = $this->request->param('id');
        $res = $this->costCheckService->check($type_name, $status, $ids);
        return json($res);
    }

    public function index50()
    {
        return $this->index(50, 'index50');
    }

    public function index100()
    {
        return $this->index(100, 'index100');
    }

    public function index200()
    {
        return $this->index(200, 'index100');
    }

    /**
     * 修改字段--备注修改
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/29
     */
    public function editUnit()
    {
        $param = [
            'id' => $this->request->param('id/d', 0),
            'field' => $this->request->param('field/s', 0),
            'value' => $this->request->param('value/s', 0),
        ];
        switch ($param['field']) {
            default:
                $temp = db('cost_check')->where([
                    ['id', '=', $param['id']],
                ])->update([
                    $param['field'] => $param['value'],
                ]);
                if ($temp == 1) {
                    return $this->Json(1, '修改成功', $temp);
                }
                return $this->Json(10, '修改失败', $temp);
                break;
        }
    }

    /**
     * 补损跟进
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/29
     */
    public function coverLoss($status = 0, $template = 'cover_loss')
    {
        if ($this->request->isAjax() || $this->request->param('export/d', 0) || $this->request->param('ajaxflag/d', 0) == 1) {
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $where = $this->_where_coverLoss([$status]);
            $field = "cc.id,cc.type,cc.return_num,cc.order_material_id,cc.order_id,cc.client_ordernum,cc.create_time as check_create_time
                ,cc.remark,cc.admin_id,cc.update_time ,cc.update_time_0,cc.param1,cc.param2
                ,o.order_price,o.sku,o.create_time
                ,o.status as order_status,o.caigou_status,o.caichuang_status,o.chejian_status,o.tail_status,o.real_shipment_status
                ,ft.name as factory_name
                ,s.pic,s.ori_pic
                ,m.type as material_type ,m.name as material_name,m.color,m.fabric_width
                ,om.customer_price,om.tiaoshu,om.true_fabric_width,om.fabric_width_once
                ,su.username as admin_id_username
,group_concat(distinct sf.id ,',', sf.billing_caigou_kgcount,',', sf.billing_caigou_count_feed SEPARATOR ';') as sf_list
,group_concat(distinct cs.id ,',', cs.type,',', cs.length,',', cs.weight_shrink SEPARATOR ';') as cs_list
                ";
            $list = db('cost_check cc')
                ->field($field)
                ->join('order o', 'cc.order_id=o.id', 'left')
                ->join('factory ft', 'o.factory_id=ft.id', 'left')
                ->join('sku s', 'o.sku=s.sku', 'left')
                ->join('order_material om', 'cc.order_material_id=om.mid', 'left')
                ->join('checkcloth_shrink cs', "om.order_id =cs.order_id and om.material_id=cs.material_id and cs.is_return=0", 'left')
                ->join('material m', 'om.material_id=m.id', 'left')
                ->join('system_user su', "cc.admin_id=su.id", 'left')
                ->join('stall_feed sf', "cc.order_material_id=sf.order_material_id", 'left')
                ->where($where)
                ->page($page)->limit($limit)
                ->group('cc.id')
                ->orderRaw('cc.id desc')
                ->select();
            $count = db('cost_check cc')
                ->join('order o', 'cc.order_id=o.id', 'left')
                ->where($where)
//                    ->group('cc.id')
                ->count();
            $stallsKV = getStallsKV();
            foreach ($list as $k => $v) {
                $list[$k]['status_txt'] = $this->_get_order_status_txt($v);
                $list[$k]['type_txt'] = $this->typeMap[$v['type']];
                //数据处理
                $list[$k]['factory_name'] = trim($v['factory_name']);
                $list[$k]['material_type'] = trim($v['material_type']);
                $list[$k]['material_name'] = trim($v['material_name']);
                $v['create_time'] > 0 ? $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']) : $list[$k]['create_time'] = '';
                $list[$k]['check_create_time']=date('Y-m-d H:i', $v['check_create_time']);
                //档口
                $omiList = db('order_material_item')->where(["order_material_id" => $v['order_material_id'], 'flag_del' => 0,])->limit(1)->find();
                $list[$k]['stalls_name'] = $omiList['stalls_id'] > 0 ? $stallsKV[$omiList['stalls_id']] ?? '' : '';
                $list[$k]['coverLossInfo'] = $coverLossInfo = $this->costCheckService->coverLossInfoDataDealWith($v);
                $list[$k]['true_num_txt'] = "";
                $list[$k]['cover_loss_txt'] = "";
                switch ($v['type']) {
                    case 10000:
                        $list[$k]['true_num_txt'] = "实际幅宽:{$coverLossInfo[10000]['true_num']}<br/>
                                                   客户幅宽:{$coverLossInfo[10000]['user_num']} ";
                        $list[$k]['cover_loss_txt'] = ($coverLossInfo[10000]['user_num'] - $coverLossInfo[10000]['true_num']) > 0
                            ? ($coverLossInfo[10000]['user_num'] - $coverLossInfo[10000]['true_num']) . '米' : '';
                        break;
                    case 10001:
                        $list[$k]['true_num_txt'] = "实际公斤:{$coverLossInfo[10001]['true_num']}<br/>
                                                   开单公斤:{$coverLossInfo[10001]['user_num']} ";
                        $list[$k]['cover_loss_txt'] = ($coverLossInfo[10001]['user_num'] - $coverLossInfo[10001]['true_num']) > 0
                            ? ($coverLossInfo[10001]['user_num'] - $coverLossInfo[10001]['true_num']) . '公斤' : '';
                        break;
                    case 10002:
                        $list[$k]['true_num_txt'] = "实际米数:{$coverLossInfo[10002]['true_num']}<br/>
                                                   开单米数:{$coverLossInfo[10002]['user_num']} ";
                        $list[$k]['cover_loss_txt'] = ($coverLossInfo[10002]['user_num'] - $coverLossInfo[10002]['true_num']) > 0
                            ? ($coverLossInfo[10002]['user_num'] - $coverLossInfo[10002]['true_num']) . '米' : '';
                        break;
                }
                $v['update_time'] > 0 ? $list[$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']) : $list[$k]['update_time'] = '';
                $v['update_time_0'] > 0 ? $list[$k]['update_time_0'] = date('Y-m-d H:i:s', $v['update_time_0']) : $list[$k]['update_time_0'] = '';
            }
            $result = [
                'code' => 0,
                'msg' => '',
                'data' => $list,
                'count' => $count,
            ];
            return json($result);
        }
        $factoryKV = getFactoryKV(false);
        $this->assign('factoryKV', [0 => '请选择'] + $factoryKV);
        $this->assign('status', $status);
        return $this->fetch($template);
    }

    private function _where_coverLoss($status = [])
    {
        $where = [];
        $where[] = ['cc.status', 'in', $status];
        $where[] = ['cc.type', '>=', 10000];
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $sku = $this->request->param('sku/s', '');
        $createDateRange = $this->request->param('create_date_range/s', '');
        $type = $this->request->param('type/d', 0);
        $factorId = $this->request->param('factory_id/d', 0);
        if ($clientOrdernum != '') {
            $where[] = ['cc.client_ordernum', '=', $clientOrdernum];
        }
        if ($sku != '') {
            $where[] = ['o.sku', 'like', "%" . $sku . "%"];
        }
        if ($factorId) {
            $where[] = ['o.factory_id', '=', $factorId];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['o.create_time', 'between', [$startTime, $endTime + 86399]];
        }
        if ($type > 0) {
            $where[] = ['cc.type', '=', $type - 1];
        }
        return $where;
    }

    /**
     * 统计信息
     * @author zhuguosen 905502314@qq.com
     * @date 2022/6/30
     */
    public function statistics()
    {
        $type_name = $this->request->param('type_name/s', 'hejia');
        $result = [];
        switch ($type_name) {
            case 'hejia':
                $where = $this->_where_index([0, 50, 100, 200]);
                //统计信息
                $statistics = db('cost_check cc')
                    ->field("cc.status,count(*) as count")
                    ->join('order o', 'cc.order_id=o.id', 'left')
                    ->join('order_ext ext', 'cc.order_id=ext.order_id', 'left')
                    ->join('factory ft', 'o.factory_id=ft.id', 'left')
                    ->join('sku s', 'o.sku=s.sku', 'left')
                    ->join('order_material om', 'cc.order_material_id=om.mid', 'left')
                    ->join('material m', 'om.material_id=m.id', 'left')
                    ->join('system_user su', "cc.admin_id=su.id", 'left')
                    ->where($where)
                    ->group('cc.status')
                    ->select();
                foreach ($statistics as $k => $v) {
                    $result[$v['status']] = $v['count'];
                }
                break;
            case 'buxien':
                $where = $this->_where_coverLoss([0, 50, 100]);
                //统计信息
                $statistics = db('cost_check cc')
                    ->field("cc.status,count(*) as count")
                    ->join('order o', 'cc.order_id=o.id', 'left')
                    ->where($where)
//                    ->group('cc.id')
                    ->group('cc.status')
                    ->select();
                foreach ($statistics as $k => $v) {
                    $result[$v['status']] = $v['count'];
                }
                break;
        }
        return $this->Json(1, '', $result);
    }

    /**
     * 统计信息--表格
     * @author zhuguosen 905502314@qq.com
     * @date 2022/7/5
     */
    public function statisticsDetail()
    {
        $type_name = $this->request->param('type_name/s', 'hejia');
        $data = $result = [];
        switch ($type_name) {
            case 'hejia'://
                $sql = "SELECT c.type
,COUNT(*) as all_num
,COUNT(DISTINCT c.order_id) as order_num
,COUNT(if(c.param1>0,1,null)) as he_num
,COUNT(if(c.status=50,1,null)) as he_go_num
,COUNT(if(c.status=100,1,null)) as he_yes_num
,sum(c.param1) as he_sum
FROM wx_cost_check c
WHERE 1=1 and c.type<10000
GROUP BY c.type";
                $info = db()->query($sql);
                $result['count'] = count($info);
                $result['he_sum_all'] = 0;
                foreach ($this->type_0Map as $k => $v) {
                    foreach ($info as $k2 => $v2) {
                        if ($k == $v2['type']) {
                            $data[] = [
                                'type_txt' => $v,
                                'order_num' => $v2['order_num'],
                                'he_num' => $v2['he_num'],
                                'submit_np' => round(($v2['he_num'] / $v2['order_num']) * 100) . '%',
                                'he_yes_num' => $v2['he_yes_num'],
                                'yes_np' => round(($v2['he_yes_num'] / $v2['order_num']) * 100) . '%',
                                'he_sum' => $v2['he_sum'],
                            ];
                            $result['he_sum_all'] += $v2['he_sum'];
                            break;
                        }
                    }
                }
                $result['he_sum_all'] = sprintf('%0.2f', $result['he_sum_all']);
                $result['data'] = $data;
                break;
            case 'buxien':
                $sql = "SELECT c.type
,COUNT(*) as all_num
,COUNT(DISTINCT c.order_id) as order_num
,COUNT(if(c.status=100,1,null)) as he_yes_num
,sum(c.param1) as he_sum
FROM wx_cost_check c
WHERE 1=1 and c.type>=10000
GROUP BY c.type";
                $info = db()->query($sql);
                $result['count'] = count($info);
                $result['he_sum_all'] = 0;
                foreach ($this->type_10000Map as $k => $v) {
                    foreach ($info as $k2 => $v2) {
                        if ($k == $v2['type']) {
                            $data[] = [
                                'type_txt' => $v,
                                'order_num' => $v2['order_num'],
                                'he_yes_num' => $v2['he_yes_num'],
                                'yes_np' => round(($v2['he_yes_num'] / $v2['order_num']) * 100) . '%',
                                'he_sum' => $v2['he_sum'],
                            ];
                            $result['he_sum_all'] += $v2['he_sum'];
                            break;
                        }
                    }
                }
                $result['he_sum_all'] = sprintf('%0.2f', $result['he_sum_all']);
                $result['data'] = $data;
                break;
        }
        return $this->Json(1, '', $result);
    }

    public function coverLoss50()
    {
        return $this->coverLoss(50, 'cover_loss50');
    }

    public function coverLoss100()
    {
        return $this->coverLoss(100, 'cover_loss100');
    }

    /**
     * 查询订单号的物料信息--方便选择
     * @author zhuguosen 905502314@qq.com
     * @date 2022/7/4
     */
    public function selectMaterial()
    {
        $clientOrdernum = $this->request->param('client_ordernum/s', '');
        $list = db('order_material om')
            ->field("om.mid,m.name")
            ->join('material m', 'om.material_id=m.id', 'left')
            ->where([
                ['om.client_ordernum', '=', $clientOrdernum],
                ['om.material_id', '>', 0],
                ['om.caigou_show', '<>', 0],// 去除不在采购进度显示条目
            ])
            ->select();
        $result = [
            'code' => count($list) > 0 ? 1 : 0,
            'msg' => '',
            'data' => $list,
        ];
        return json($result);
    }
}